{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2023 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# tasks_and_workers_assignment_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/examples/tasks_and_workers_assignment_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/python/tasks_and_workers_assignment_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "Tasks and workers to group assignment to average sum(cost) / #workers.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Sequence\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "\n",
    "class ObjectivePrinter(cp_model.CpSolverSolutionCallback):\n",
    "    \"\"\"Print intermediate solutions.\"\"\"\n",
    "\n",
    "    def __init__(self):\n",
    "        cp_model.CpSolverSolutionCallback.__init__(self)\n",
    "        self.__solution_count = 0\n",
    "\n",
    "    def on_solution_callback(self):\n",
    "        print(\n",
    "            \"Solution %i, time = %f s, objective = %i\"\n",
    "            % (self.__solution_count, self.WallTime(), self.ObjectiveValue())\n",
    "        )\n",
    "        self.__solution_count += 1\n",
    "\n",
    "\n",
    "def tasks_and_workers_assignment_sat():\n",
    "    \"\"\"Solve the assignment problem.\"\"\"\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    # CP-SAT solver is integer only.\n",
    "    task_cost = [24, 10, 7, 2, 11, 16, 1, 13, 9, 27]\n",
    "    num_tasks = len(task_cost)\n",
    "    num_workers = 3\n",
    "    num_groups = 2\n",
    "    all_workers = range(num_workers)\n",
    "    all_groups = range(num_groups)\n",
    "    all_tasks = range(num_tasks)\n",
    "\n",
    "    # Variables\n",
    "\n",
    "    ## x_ij = 1 if worker i is assigned to group j\n",
    "    x = {}\n",
    "    for i in all_workers:\n",
    "        for j in all_groups:\n",
    "            x[i, j] = model.NewBoolVar(\"x[%i,%i]\" % (i, j))\n",
    "\n",
    "    ## y_kj is 1 if task k is assigned to group j\n",
    "    y = {}\n",
    "    for k in all_tasks:\n",
    "        for j in all_groups:\n",
    "            y[k, j] = model.NewBoolVar(\"x[%i,%i]\" % (k, j))\n",
    "\n",
    "    # Constraints\n",
    "\n",
    "    # Each task k is assigned to a group and only one.\n",
    "    for k in all_tasks:\n",
    "        model.Add(sum(y[k, j] for j in all_groups) == 1)\n",
    "\n",
    "    # Each worker i is assigned to a group and only one.\n",
    "    for i in all_workers:\n",
    "        model.Add(sum(x[i, j] for j in all_groups) == 1)\n",
    "\n",
    "    # cost per group\n",
    "    sum_of_costs = sum(task_cost)\n",
    "    averages = []\n",
    "    num_workers_in_group = []\n",
    "    scaled_sum_of_costs_in_group = []\n",
    "    scaling = 1000  # We introduce scaling to deal with floating point average.\n",
    "    for j in all_groups:\n",
    "        n = model.NewIntVar(1, num_workers, \"num_workers_in_group_%i\" % j)\n",
    "        model.Add(n == sum(x[i, j] for i in all_workers))\n",
    "        c = model.NewIntVar(0, sum_of_costs * scaling, \"sum_of_costs_of_group_%i\" % j)\n",
    "        model.Add(c == sum(y[k, j] * task_cost[k] * scaling for k in all_tasks))\n",
    "        a = model.NewIntVar(0, sum_of_costs * scaling, \"average_cost_of_group_%i\" % j)\n",
    "        model.AddDivisionEquality(a, c, n)\n",
    "\n",
    "        averages.append(a)\n",
    "        num_workers_in_group.append(n)\n",
    "        scaled_sum_of_costs_in_group.append(c)\n",
    "\n",
    "    # All workers are assigned.\n",
    "    model.Add(sum(num_workers_in_group) == num_workers)\n",
    "\n",
    "    # Objective.\n",
    "    obj = model.NewIntVar(0, sum_of_costs * scaling, \"obj\")\n",
    "    model.AddMaxEquality(obj, averages)\n",
    "    model.Minimize(obj)\n",
    "\n",
    "    # Solve and print out the solution.\n",
    "    solver = cp_model.CpSolver()\n",
    "    solver.parameters.max_time_in_seconds = 60 * 60 * 2\n",
    "    objective_printer = ObjectivePrinter()\n",
    "    status = solver.Solve(model, objective_printer)\n",
    "    print(solver.ResponseStats())\n",
    "\n",
    "    if status == cp_model.OPTIMAL:\n",
    "        for j in all_groups:\n",
    "            print(\"Group %i\" % j)\n",
    "            for i in all_workers:\n",
    "                if solver.BooleanValue(x[i, j]):\n",
    "                    print(\"  - worker %i\" % i)\n",
    "            for k in all_tasks:\n",
    "                if solver.BooleanValue(y[k, j]):\n",
    "                    print(\"  - task %i with cost %i\" % (k, task_cost[k]))\n",
    "            print(\n",
    "                \"  - sum_of_costs = %i\"\n",
    "                % (solver.Value(scaled_sum_of_costs_in_group[j]) // scaling)\n",
    "            )\n",
    "            print(\"  - average cost = %f\" % (solver.Value(averages[j]) * 1.0 / scaling))\n",
    "\n",
    "\n",
    "tasks_and_workers_assignment_sat()\n",
    "\n",
    "\n",
    "def main(argv: Sequence[str]) -> None:\n",
    "    if len(argv) > 1:\n",
    "        raise app.UsageError(\"Too many command-line arguments.\")\n",
    "    tasks_and_workers_assignment_sat()\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}
